package org.cl.persist.file.controller;

import com.github.xiaoymin.knife4j.core.util.StrUtil;
import com.mongodb.client.result.UpdateResult;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.springboot.gls.ex.request.exception.ExceptionEnum;
import org.springboot.gls.ex.request.ret.R;
import org.springboot.gls.ex.request.time.RTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotNull;
import java.io.File;
import java.io.IOException;

/**
 * @author cl
 */
@Slf4j
@RestController
@Validated
@RequestMapping("/file")
public class FileController {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 单文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R upload(@NotNull @RequestParam("file") MultipartFile file) {
        return R.ok(uploadHandler(file));
    }

    /**
     * 多文件上传
     * @param files
     * @return
     */
    @PostMapping("/uploads")
    public R uploads(@RequestParam("files") MultipartFile[] files) {
        if (files == null) {
            return R.failed();
        }
        for (MultipartFile file : files) {
            uploadHandler(file);
        }
        return R.ok();
    }

    private boolean uploadHandler(MultipartFile file) {
        // 获取文件名，带后缀
        String originalFilename = file.getOriginalFilename();
        ExceptionEnum.CLIENT_CODE.assertFalse(StrUtil.isBlank(originalFilename), "40001");
        int lastIndex = originalFilename.lastIndexOf(".");
        ExceptionEnum.CLIENT_CODE.assertTrue(lastIndex > 0, "40001");
        // 获取文件名 不包括后缀
        String fileName = originalFilename.substring(0, lastIndex);
        // 获取文件的后缀
        String fileSuffix = originalFilename.substring(lastIndex).toLowerCase();
        long size = file.getSize();
        String fileSize = size + "b";
        if (size > 1024 * 1024) {
            fileSize = String.format("%.2fM", size / (1024 * 1024 * 1.0));
        } else if (size > 1024) {
            fileSize = String.format("%.2fKb", size / (1024 * 1.0));
        }
        log.info("upload file [fileName: {}, size: {}]", originalFilename, fileSize);
        try {
            String filePath = "D://tmp/";
            File dest = new File(filePath + fileName + "_" + System.currentTimeMillis() + fileSuffix);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            if (!dest.exists()) {
                dest.createNewFile();
            }
            file.transferTo(dest);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    @GetMapping("/gets")
    @RTime
    public R getFileList() {
        // 添加
        String name = "MongoDb hello World!";
        Runoob runoob = new Runoob();
        runoob.setName(name);
        mongoTemplate.save(runoob);

        // 查询
        Query query = new Query(Criteria.where("name").is(name));
        System.out.println(mongoTemplate.findOne(query , Runoob.class));

        // 修改
        name = "MongoDb wo lai le!";
        Update update= new Update().set("name", name);
        //更新查询返回结果集的第一条
        UpdateResult result = mongoTemplate.updateFirst(query, update, Runoob.class);
        System.out.println(result.getModifiedCount());

        // 查询
        query = new Query(Criteria.where("name").is(name));
        System.out.println(mongoTemplate.findOne(query , Runoob.class));

        // 删除
        mongoTemplate.remove(query, Runoob.class);
        return R.failed();
    }

    @Getter
    @Setter
    @ToString
    public static class Runoob {
        String name;
        String id;
    }
}
